package com.hxzy.system.service.impl;

import com.hxzy.common.constant.Constants;
import com.hxzy.common.utils.StringUtils;
import com.hxzy.system.domain.SysConfig;
import com.hxzy.system.mapper.SysConfigMapper;
import com.hxzy.system.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 类说明
 *
 * @author admin
 * @date 2021-09-25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysConfigServiceImpl extends CommonServiceImpl<SysConfig,Long> implements SysConfigService {

    private SysConfigMapper sysConfigMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public void setSysConfigMapper(SysConfigMapper sysConfigMapper) {
        this.sysConfigMapper = sysConfigMapper;
        super.setMyBatisBaseDao(sysConfigMapper);
    }

    @Override
    public int checkConfigKeyUnique(Long configId, String configKey) {
        return this.sysConfigMapper.checkConfigKeyUnique(configId,configKey);
    }

    @Override
    public String selectValueByKey(String configKey) {
        //为了值优化，采用redis来进行缓存  sys_config:sys.account.captchaOnOff
        String redisKey= Constants.SYS_CONFIG_KEY+configKey;
        String redisValue=this.stringRedisTemplate.opsForValue().get(redisKey);
        if(StringUtils.isNotBlank(redisValue)){
            return redisValue;
        }

        //没有值查询数据库
        String value=this.sysConfigMapper.selectValueByKey(configKey);
        if(StringUtils.isNotBlank(value)){
            //写放到redis缓存中
            this.stringRedisTemplate.opsForValue().set(redisKey,value);
        }

        return value;
    }

    @Override
    public List<SysConfig> selectAll() {
        return this.sysConfigMapper.selectAll();
    }
}
